//加载公共样式
require('../../assets/css/index.less')

//加载自己的样式
require('./login.less')

//引入工具函数
const request = require('../../assets/utils/request')

window.onload = () => {
  //获取dom
  const phoneIpt = document.querySelector('#phoneIpt')
  const pwdIpt = document.querySelector('#pwdIpt')
  const submit = document.querySelector('#submit')

  //点击注册按钮
  submit.addEventListener('click', () => {
    //收集错误信息
    let errMsg = ''
    //开始验证
    if (!/^1[3-9]\d{9}$/.test(phoneIpt.value)) {
      errMsg = '手机号格式不正确'
      //验证码全部转为小写 方便用户
    } else if (!/^\w{3,6}$/.test(pwdIpt.value)) {
      errMsg = '密码3-6位'
    } else {
      console.log('验证通过 可以发送请求')
      request
        .post('/api/user/login', {
          account: phoneIpt.value,
          password: pwdIpt.value,
        })
        .then(res => {
          console.log('res.data :>> ', res.data)
          //1 解构数据
          let {errno, data} = res.data
          //2 判断
          if (errno === 0) {
            //3 处理数据
            localStorage.setItem('token', 'Bearer ' + data.token)
            alert('登录成功')
            //4 跳转首页
            window.location.href = './home.html'
          }
        })
        .catch(err => {
          console.log('err :>> ', err)
        })
    }

    if (errMsg) {
      alert(errMsg)
    }
  })
}
